var icdev = 0; //设备句柄
var lock = new Lock()
var data = undefined
var resetData = undefined
var uid = undefined
var msg = {} ;
var layer = layui.layer
var form = layui.form
var status = 0 // 0 未复位   1 已复位
var reader = getReader(async function(){
    // 连接USB读卡器
    try {
        reader.connectUsb(); //连接usb设备
        await lock.wait()
    } catch (e) {
        msg.value = msg.value + e.Message + "\n";
    }
}); //获取reader对象, getReader会自动连接ReaderService服务
if (reader == null) {
    alert('您的浏览器不支持读写器服务.');
}

// 设置回调
reader.onResult(function (ret) {
    data = ret
    console.log("返回："+data.resultData)
    lock.notify(data)
    //执行成功
    if (ret.result == 0) {
        switch (ret.functionId) {
            case READER_CMD._reader_server_connect:
                break;
            case READER_CMD._reader_cmd_connect:
                icdev = parseInt(ret.resultData); //连接成功后, resultData 为设备句柄
                msg.value = msg.value + "读写器连接成功.\n";
                break;
            case READER_CMD._reader_cmd_disconnect:
                msg.value = msg.value + "读写器断开连接成功.\n";
                break;
            case READER_CMD._reader_cmd_beep:
                msg.value = msg.value + "读写器鸣响成功.\n";
                break;
            case READER_CMD._reader_cmd_rf_card:
            case READER_CMD._reader_cmd_rf_card_b:
                msg.value = msg.value + "寻卡成功, 卡片序列号: " + ret.resultData + "\n";
                break;
            case READER_CMD._reader_cmd_c_cpu_reset:
                msg.value = msg.value + "非接触式 TypeA CPU 卡复位成功. 复位信息: " + ret.resultData + "\n";
                break;
            case READER_CMD._reader_cmd_c_cpu_reset_b:
                msg.value = msg.value + "非接触式 TypeB CPU 卡复位成功.\n";
                break;
            case READER_CMD._reader_cmd_rf_halt:
            case READER_CMD._reader_cmd_rf_halt_b:
                msg.value = msg.value + "终止卡片操作成功.\n";
                break;
            case READER_CMD._reader_cmd_uc_auth_key:
                msg.value = msg.value + "Ultralight C 校验密码成功.\n";
                break;
            case READER_CMD._reader_cmd_uev_auth_key:
                msg.value = msg.value + "Ultralight EV 校验密码成功.\n";
                break;
            case READER_CMD._reader_cmd_u_read:
                msg.value = msg.value + "Ultralight / Ultralight C 读数据成功. 读取到的数据: " + ret.resultData + "\n";
                break;
            case READER_CMD._reader_cmd_u_write:
                msg.value = msg.value + "Ultralight / Ultralight C 写数据成功.\n";
                break;
            case READER_CMD._reader_cmd_uc_change_key:
                msg.value = msg.value + "更改  Ultralight C 密码成功.\n";
                break;
        }
    } else {
        //失败打印错误信息
        msg.value = msg.value + ret.resultData + "\n";
    }
    // console.log(data)
});


// 定时寻卡
async function find_card(){
    try {
        reader.rfCard(icdev, 1);
        await lock.wait()
        uid = data.resultData
        console.log(uid)
        if(uid != "请求失败。" && uid != "设备未连接。"){
            clearInterval(timer)
            status = 1
            cardNo = uid
            $("input[name='cardNo']").val(uid)
            // 发起网络请求获取用户信息
            $.ajax({
                url: "/business/getStaffByCardNo?cardNo=" + cardNo
                , type: "get"
                , success: function (data) {
                    if (data.code == 500) {
                        layer.close(layer.index);
                        layer.msg(data.msg);
                        setTimeout(function () {
                            window.location.reload();
                        }, 3000);
                        return;
                    }else if (data.code == 200){
                        console.log("data",data.data);
                        $("#staffId").val(data.data.id);
                        $("#staffName").val(data.data.name);
                        $("#logo").val(data.data.picture);
                        $("#picture").attr("src",data.data.picture);
                        $("#staffBh").val(data.data.bh);
                        // 发起网络请求获取健康码
                        $.ajax({
                            url: "/business/getQrCode?staffId=" + data.data.id
                            , type: "get"
                            , success: function (data2) {
                                console.log(data2.data);
                                if (data2.code == 200) {
                                    $( "#qrCode" ).qrcode({
                                        render: "canvas" , // 渲染方式有table方式（IE兼容）和canvas方式
                                        width: 200, //宽度
                                        height: 200, //高度
                                        text: "www.baidu.com" , //内容
                                        typeNumber: -1, //计算模式
                                        correctLevel: 2, //二维码纠错级别
                                        background: "#ffffff" , //背景颜色
                                        foreground: data2.data //二维码颜色
                                    });
                                    //判断是进店还是离店
                                    $.ajax({
                                        url: "/business/get_last_trail?staffBh=" + data.data.bh
                                        , type: "get"
                                        , success: function (data3) {
                                            console.log("data3:" + data3.data);
                                            if (data3.code == 200) {
                                                if (data3.data) {
                                                    layer.prompt({
                                                        value: '',
                                                        title: '请选择进店或离店',
                                                        btn: ['确定'], //按钮，
                                                        area: ['500px', '240px'],
                                                        btnAlign: 'c',
                                                        content :
                                                                '<div class="layui-input-inline">' +
                                                                '<span style="cursor: pointer;" onclick="selectRedio(0)"><input type="radio" id="jd" name="business" value="0" title="进店">进店</span>' +
                                                                '<span style="cursor: pointer;" onclick="selectRedio(1)"><input type="radio" id="ld" name="business" value="1" title="离店" checked style="margin-left: 25px;">离店</span>' +
                                                                '</div>',
                                                        yes: function (index,layero) {
                                                            var content = $("input[name='business']:checked").val();
                                                            if (content == "0") {
                                                                $.ajax({
                                                                    url: "/business/addTrail?staffBh=" + data.data.bh + "&type=" + 0
                                                                    , type: "get"
                                                                    , success: function (data4) {
                                                                        console.log(data4.data);
                                                                        if (data4.code == 200) {
                                                                            layer.msg("进店成功");
                                                                            setTimeout(function () {
                                                                                window.location.reload();
                                                                            }, 2000);
                                                                        }else if (data4.code == 500) {
                                                                            layer.msg(data4.msg);
                                                                            return
                                                                        }else {
                                                                            layer.msg("拒绝访问");
                                                                        }
                                                                    }
                                                                });
                                                            }else {
                                                                $.ajax({
                                                                    url: "/business/addTrail?staffBh=" + data.data.bh + "&type=" + 1
                                                                    , type: "get"
                                                                    , success: function (data4) {
                                                                        console.log(data4.data);
                                                                        if (data4.code == 200) {
                                                                            layer.msg("离店成功");
                                                                            setTimeout(function () {
                                                                                window.location.reload();
                                                                            }, 2000);
                                                                        }else if (data4.code == 500) {
                                                                            layer.msg(data4.msg);
                                                                            return
                                                                        }else {
                                                                            layer.msg("拒绝访问");
                                                                        }
                                                                    }
                                                                });
                                                            }
                                                        }
                                                    }, function(value,index){
                                                        layer.close(index);
                                                    });
                                                }else {
                                                    $.ajax({
                                                        url: "/business/addTrail?staffBh=" + data.data.bh + "&type=" + 0
                                                        , type: "get"
                                                        , success: function (data4) {
                                                            console.log(data4.data);
                                                            if (data4.code == 200) {
                                                                layer.msg("进店成功");
                                                                setTimeout(function () {
                                                                    window.location.reload();
                                                                }, 2000);
                                                            }else if (data4.code == 500) {
                                                                layer.msg(data4.msg);
                                                            }else {
                                                                layer.msg("拒绝访问");
                                                            }
                                                        }
                                                    });
                                                }
                                            }
                                        }
                                    });
                                }
                            }
                        });
                    }
                }
            });
            form.render()
        }
        reader.mifareCpuReset(icdev);
        await lock.wait()
        resetData = data.resultData
    } catch (e) {
        console.log(e)
        // msg.value = msg.value + e.Message + "\n";
    }
}

timer = setInterval(find_card , 1000)


function checkRs(){
    switch(data.resultData) {
        case "6200":
            return "警告 信息未提供"
        case "6281":
            return "警告 回送数据可能"
        case "6282":
            return "警告 文件长度小于Le"
        case "6283" :
            return "警告 选中的文件无效"
        case "6284":
            return "警告 FCI格式与P2指定的不符"
        case "6300":
            return "警告 鉴别失败"
        case "63C2":
            return "警告 校验失败（允许重试次数2）"
        case "63C1":
            return "警告 校验失败（允许重试次数1）"
        case "6400":
            return "状态标志位没有变"
        case "6581":
            return "内存失败"
        case "6700":
            return "长度错误"
        case "6882" :
            return "不支持安全报文"
        case "6981":
            return "命令与文件结构不相容，当前文件非所需文件"
        case "6982":
            return "操作条件（AC）不满足，没有校验PIN"
        case "6983":
            return "您的卡已被锁定"
        case "6984":
            return "随机数无效，引用的数据无效"
        case "6985":
            return "使用条件不满足"
        case "6986":
            return "不满足命令执行条件（不允许的命令，INS有错）"
        case "6987":
            return "MAC丢失"
        case "6988":
            return "MAC不正确"
        case "698D":
            return "保留"
        case "6A80":
            return "数据域参数不正确"
        case "6A81":
            return "功能不支持；创建不允许；目录无效；应用锁定"
        case "6A82":
            return "该文件未找到"
        case "6A83":
            return "该记录未找到"
        case "6A84":
            return "文件预留空间不足"
        case "6A86":
            return "P1或P2不正确"
        case "6A88":
            return "引用数据未找到"
        case "6B00":
            return "参数错误"
        case "6C":
            return "Le长度错误"
        case "6E00":
            return "不支持的类：CLA有错"
        case "6F00":
            return "数据无效"
        case "6F01" :
            return "连接中断"
        case "6D00":
            return "不支持的指令代码"
        case "9301":
            return "您的卡余额不足"
        case "9302":
            return "MAC2错误"
        case "9303":
            return "应用被永久锁定"
        case "9401":
            return "您的卡余额不足"
        case "9402":
            return "交易计数器达到最大值"
        case "9403":
            return "密钥索引不支持"
        case "9406":
            return "所需MAC不可用"
        case "6900":
            return "不能处理"
        case "6901":
            return "命令不接受（无效状态）"
        case "61":
            return "正常 需发GET RESPONSE命令"
        case "6600":
            return  "接收通讯超时"
        case "6601":
            return "接收字符奇偶错"
        case "6602":
            return "校验和不对"
        case "6603":
            return "警告 当前DF文件无FCI"
        case "6604":
            return "警告 当前DF下无SF或KF"
        case "6E81":
            return "卡片已离开"
        default:
            return undefined
    }
}